﻿using System;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Threading;
using Ensemble;

namespace EnsembleLauncher
{
    internal static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        public static void Main(string[] args)
        {
            Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
            Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture;

            var isDebugging = Debugger.IsAttached || args.Contains(EnsembleApp.CmdArgDebug);
            var isRunFromEditor = args.Contains(EnsembleApp.CmdArgEditor);
            var isProfiling = args.Contains(EnsembleApp.CmdArgProfiling);
            if (isDebugging || isRunFromEditor) ShowConsole();

            EnsembleApp.Init(EnsembleApp.ExecutionEnvironment.Launcher,
                EnsembleApp.ExecutionContext.Game,
                new DefaultPluginLoader(),
                args);

            var options = new WindowOptions()
            {
                Width = EnsembleApp.UserData.GfxWidth,
                Height = EnsembleApp.UserData.GfxHeight,
                ScreenMode = isDebugging ? ScreenMode.Window : EnsembleApp.UserData.GfxMode,
                RefreshMode = (isDebugging || isProfiling) ? RefreshMode.NoSync : EnsembleApp.UserData.RefreshMode,
                Title = EnsembleApp.AppData.AppName,
                SystemCursorVisible = isDebugging || EnsembleApp.UserData.SystemCursorVisible
            };
            using (var window = EnsembleApp.OpenWindow(options))
            {
                window.Run();
            }

            EnsembleApp.Terminate();
        }

        private static bool hasConsole = false;
        public static void ShowConsole()
        {
            if (hasConsole) return;
            SafeNativeMethods.AllocConsole();
            hasConsole = true;
        }
    }
}
